package com.eale.inteligentcloud.controller;


import com.eale.inteligentcloud.common.Result;
import com.eale.inteligentcloud.domain.ICPEquipment;
import com.eale.inteligentcloud.domain.ICPOrder;
import com.eale.inteligentcloud.domain.ICPProduct;
import com.eale.inteligentcloud.exception.ParamValidatedException;
import com.eale.inteligentcloud.service.EquipmentService;
import com.eale.inteligentcloud.service.OrderService;
import com.eale.inteligentcloud.service.ProductService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;



/**
 * @author Sail
 * 2018/11/21
 */
@RequestMapping("order")
@RestController
public class OrderController {

    @Autowired
    OrderService service;
    
    @Autowired
    ProductService productservice;
    
    @Autowired
    EquipmentService equipmentservice;
    
    /**
     * 增加Order
     *
     * @return
     */
    @PostMapping("order.do")
    public Object addOrder(@Validated ICPOrder order, BindingResult bindres) {
        if (bindres.hasErrors()) {
            throw new ParamValidatedException(bindres.getAllErrors());
        }
        Optional<ICPProduct> opt = productservice.findByproName(order.getoProduct().getProName());

		if (!opt.isPresent()) {
			return new Result(1, null, "请输入正确的产品");
		}
		
		order.setoState(1);
		order.setoPlacetime(System.currentTimeMillis());
        order.setoProduct(opt.get());
        order.setoCtime(System.currentTimeMillis());
        order.setoCuser((long) 1);//测试用户
        order.setoUptime(System.currentTimeMillis());
        order.setoUpuser((long) 1);//测试用户
        //存入数据库
        service.PlaceOrder(order);
        return order;
    }

    /**
     * 按订单状态分页查询
     */
    @GetMapping("searchOrderState.do")
    public Object getStatePage(Integer oState, int page, int total) {
        Pageable pageable = PageRequest.of(page, total);
        List<ICPOrder> dbOrder = service.findByStatePage(oState, pageable);
        if (dbOrder.size() > 0) {
            return new Result(1, dbOrder, null);
        } else {
            return new Result(1, null, "订单没有找到");
        }
    }
    
    /**
     * 按订单状态分页查询--待接单[1]
     */
    @GetMapping("searchOrderStatePage.do")
    public Object getByStatePage( int page, int total) {
        Pageable pageable = PageRequest.of(page, total);
        Integer oState=1;
        List<ICPOrder> dbOrder = service.findByStatePage(oState, pageable);
        if (dbOrder.size() > 0) {
            return new Result(1, dbOrder, null);
        } else {
            return new Result(1, null, "订单没有找到");
        }
    }
    
    /**
     * 按订单状态分页查询--已处理订单/ 已拒绝[2]/已接单[3]/生产中[4]/已完成[5]
     */
    @GetMapping("searchOrderStatePagehandled.do")
    public Object getByStatehandled( int page, int total) {
        Pageable pageable = PageRequest.of(page, total);
        List<Integer> states=new ArrayList<>();
        states.add(1);
        states.add(-1);
        List<ICPOrder> dbOrder = service.findByStatePageHandled(pageable,states);
        if (dbOrder.size() > 0) {
            return new Result(1, dbOrder, null);
        } else {
            return new Result(1, null, "订单没有找到");
        }
    }
    

    /**
     * 分页查询 全部order
     * @return
     */
    @GetMapping("orders.do")
    public Object getConditionsPage(int page, int total) {
        Pageable pageable = PageRequest.of(page, total);
        List<ICPOrder> dbOrder = service.findAllPage(pageable);
        if (dbOrder.size() > 0) {
            return new Result(1, dbOrder, null);
        } else {
            return new Result(1, null, "订单没有找到");
        }
    }
    
    /**
     * 按id查询order
     */
    @GetMapping("searchOrder.do")
    public Object getConditionsPage(Long oId) {
        Optional<ICPOrder> opt = service.findById(oId);
        if (opt.isPresent()) {
            return new Result(1, opt, null);
        } else {
            return new Result(1, null, "订单没有找到");
        }
    }

    /**
     * 按订单创建时间范围查询
     *
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("searchOrderTime.do")
    public Object getConditionsPage(Long beginTime, Long endTime, int page, int total) {
        Pageable pageable = PageRequest.of(page, total);
        List<ICPOrder> dbOrder = service.findConditionsPage(beginTime, endTime, pageable);
        if (dbOrder.size() > 0) {
            return new Result(1, dbOrder, null);
        } else {
            return new Result(1, null, "订单没有找到");
        }
    }

    /**
     * 按订单来源分页查询
     */
    @GetMapping("searchOrderSourse.do")
    public Object getSoursePage(Integer oSourse, int page, int total) {
        Pageable pageable = PageRequest.of(page, total);
        List<ICPOrder> dbOrder = service.findBySoursePage(oSourse, pageable);
        if (dbOrder.size() > 0) {
            return new Result(1, dbOrder, null);
        } else {
            return new Result(1, null, "订单没有找到");
        }
    }
    
    /**
     * 接单
     */
    @PutMapping("acceptOrder.do")
    public Object acceptOrder(Long oId) {
    	Optional<ICPOrder> opt = service.findById(oId);
		if (!opt.isPresent()) {
			return new Result(1,null,"当前订单有问题");
		}
		ICPEquipment equipment=new ICPEquipment();
//		System.out.println(opt.get().getoProduct().toString());
		ICPProduct product=new ICPProduct();
		product.setProFid(opt.get().getoProduct().getProFid());
		equipment.setEquipProduct(product);
		equipment.setEquipState(1);
		System.out.println(product.toString());
		System.out.println(equipment.toString());
		List<ICPEquipment> equipmentlist = equipmentservice.findByCondtions(equipment);
		System.err.println(equipmentlist.size());
		Double capacities = 0.0;
		for (ICPEquipment icpEquipment : equipmentlist) {
			Double capacity = icpEquipment.getEquipCapacity();
			
			capacities+=capacity*(opt.get().getoDeadline()-opt.get().getoCtime()/(1000*60*60*24));
		}
		if(capacities<opt.get().getoFinishNum()) {
			return new Result(1, null, "产能不足");
		}
		service.acceptOrder(oId);   
    	return new Result(1,null,"接单成功");
    	
    }
    
    /**
     * 拒单
     */
    @PutMapping("rejectOrder.do")
    public Object rejectOrder(Long oId,String oRemark) {
    	Optional<ICPOrder> opt = service.findById(oId);
        if(opt.isPresent()) {
        	service.rejectOrder(oId,oRemark);
            return new Result(1);
        }
        return new Result(1, null, "操作失败");
    }
    
    /**
     * 转生产计划  ostate[4]
     * @param oId
     * @return
     */
    @PutMapping("TransforOrderToPlan.do")
    public Object TransforOrderToPlan(Long oId,Long planStarttime,Long planEndtime) {
        Integer state=4;
        service.TransforOrderToPlan(oId,state,planStarttime,planEndtime);
        return new Result(1);
    }
    
    /**
     * 修改Order
     *
     * @return
     */
    @PutMapping("order.do")
    public Object updateOrder(@Validated ICPOrder order, BindingResult bindres) {
        if (bindres.hasErrors()) {
            throw new ParamValidatedException(bindres.getAllErrors());
        }
        order.setoUptime(System.currentTimeMillis());
        order.setoUpuser((long) 1);//测试用户
        
        service.updateOrder(order);
        return new Result(1);
    }

  
    
    /**
     * 删除Order
     *
     * @return
     */
    @DeleteMapping("order.do")
    public Object delOrder(Long oId) {
        
        service.deleteOrder(oId);
        return new Result(1);
    }
    /**
     * 批量删除Orders
     *
     * @return
     */
    @DeleteMapping("orders.do")
    public Object delOrders(@RequestParam(value = "oIds[]") Long[] oIds) {
        service.deleteOrders(oIds);
        return new Result(1);
    }

    /**
     * 统计所有未删除订单
     */
    @GetMapping("countOrders")
    public Object countOrders(){
        Map<String,Integer> map = new HashMap<>(6);
        Integer allOrders=service.findAllNum(-1);//全部
        Integer waitint=service.findByStateNum(1);//待接单
        Integer repulse=service.findByStateNum(2);//已拒绝
        Integer haveOrder=service.findByStateNum(3);//已接单
        Integer inProduction=service.findByStateNum(4);//生产中
        Integer achieve=service.findByStateNum(5);//已完成

        map.put("allOrders", allOrders);
        map.put("waitint", waitint);
        map.put("repulse", repulse);
        map.put("haveOrder", haveOrder);
        map.put("inProduction", inProduction);
        map.put("achieve", achieve);

        return new Result(1, map, null);
    }

    /**
     * 统计时间范围内未删除订单
     */
    @GetMapping("countOrdersTime")
    public Object countOrdersTime(Long beginTime, Long endTime){
        Integer allOrders=service.findAllNum(-1,beginTime, endTime);

        return new Result(1, allOrders, null);
    }
    
    /**
     * 按条件分页查询
     */
    @GetMapping("searchOrderConsition.do")
    public Object getOrderConsitionPage(ICPOrder order, int page, int total) {
        Pageable pageable = PageRequest.of(page, total);
        List<ICPOrder> dbOrder = service.findByConditionsPage(order, pageable);
        if (dbOrder.size() > 0) {
            return new Result(1, dbOrder, null);
        } else {
            return new Result(1, null, "订单没有找到");
        }
    }
    
}
